﻿namespace PowerSong.UserInterface
    {
    using System.Linq;
    using System.Windows;
    using PowerSong.SongDatabase;
    using System;

    /// <summary>
    /// Interaction logic for EditSongWindow.xaml
    /// </summary>
    public partial class EditSongWindow : Window
        {

        private Song existingSong = null;

        public EditSongWindow(Song existingSong = null)
            {

            InitializeComponent();

            // Show available categories and licenses
            UpdateCategories();
            UpdateLicenses();
            UpdateStyles();

            // Are we editing a song, or creating a new one?
            if (existingSong != null)
                {

                Title = "Edit Song - " + existingSong.Title;
                this.existingSong = existingSong;
                this.NameTextBox.Text = existingSong.Title;
                this.CopyrightTextBox.Text = existingSong.Copyright;
                this.LicenseComboBox.SelectedItem = existingSong.License;

                // Set authors into text box
                var firstAuthor = true;
                foreach (var author in existingSong.Authors.OrderBy(name => name))
                    {
                    if (!firstAuthor) AuthorsTextBox.Text += Environment.NewLine;
                    AuthorsTextBox.Text += author;
                    firstAuthor = false;
                    }

                // Set verses into text box
                VersesTextBox.Text = Utilities.VersesToText(existingSong.Verses);

                // Set categories
                CategoriesListBox.SetCheckedItems(existingSong.Categories, true);

                // Set default style
                DefaultStyleComboBox.SelectedItem = existingSong.DefaultStyle;

                }
            else
                {

                Title = "New Song";

                // Set license if there is a default one set
                LicenseComboBox.SelectedItem = State.Settings.DefaultLicense;

                // Set categories if there are default categories
                var defaultCategories = State.Database.Categories.GetDefaultCategories();
                foreach (CheckListBoxItem item in CategoriesListBox.Items)
                    {
                    item.IsChecked = Array.IndexOf<Category>(defaultCategories, (Category)item.Value) != -1;
                    }

                }
            
            }

        private void ManageCategoriesButton_Click(object sender, RoutedEventArgs e)
            {
            var window = new EditCategoriesWindow();
            window.ShowDialog();
            UpdateCategories();
            if (existingSong != null) CategoriesListBox.SetCheckedItems(existingSong.Categories, true);
            }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
            {
            this.DialogResult = false;
            }

        private void OKButton_Click(object sender, RoutedEventArgs e)
            {

            try
                {

                // A song title must be specified
                if (string.IsNullOrEmpty(NameTextBox.Text))
                    {
                    throw new Exception("Please specify a title for this song.");
                    }

                // Some verses must be specified
                var verses = Utilities.TextToVerses(VersesTextBox.Text);                
                if (verses.Length <= 0)
                    {
                    throw new Exception("Please give this song at least one verse.");
                    }

                // The song must be assigned at least one category
                if (CategoriesListBox.GetCheckedItems().Length == 0)
                    {
                    throw new Exception(State.Database.Categories.Count() > 0
                                        ? "Please assign at least one category to the song so that it can be found later."
                                        : "You must assign at least one category to the song." + Environment.NewLine + Environment.NewLine + "Currently, there are no categories, so please use the 'Manage' button to create a new category, then assign it to this song." + Environment.NewLine + Environment.NewLine + "You will then be able to save the song.");
                    }

                // Create a new song object, or edit the existing song object
                var song = existingSong == null ? new Song() : this.existingSong;

                // Populate some song details
                song.Title = NameTextBox.Text;
                song.Copyright = CopyrightTextBox.Text;
                song.License = (License)LicenseComboBox.SelectedItem;
                song.DefaultStyle = (PowerSong.SongDatabase.Style)DefaultStyleComboBox.SelectedItem;

                // Populate verses
                song.Verses.Clear();
                song.Verses.AddRange(verses);

                // Populate authors
                var authors = AuthorsTextBox.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                song.Authors.Clear();
                foreach (var author in authors.OrderBy(a => a))
                    {
                    var actualAuthor = author.Trim();
                    if (!string.IsNullOrEmpty(actualAuthor)) song.Authors.Add(actualAuthor);
                    }

                // Populate categories
                song.Categories.Clear();
                foreach (Category category in CategoriesListBox.GetCheckedItems())
                    {
                    song.Categories.Add(category);
                    }

                // Save the new song to the database
                State.Database.Songs.Write(song);

                // Close the window
                this.DialogResult = true;

                }
            catch (Exception ex)
                {
                Utilities.ShowErrorMessage("Cannot Save Song Details", ex.Message);
                }

            }

        private void UpdateCategories()
            {
            var categories = State.Database.Categories.GetAllCategories().OrderBy(c => c.Name).ToArray();
            var items = CheckListBoxItem.CreateItems(categories);
            CategoriesListBox.ItemsSource = items;
            }

        private void UpdateLicenses()
            {
            LicenseComboBox.Items.Clear();
            LicenseComboBox.Items.Add("(No License)");
            foreach (var license in State.Database.Licenses.GetAllLicenses().OrderBy(l => l.Name))
                {
                LicenseComboBox.Items.Add(license);
                }            
            }

        private void UpdateStyles()
            {
            DefaultStyleComboBox.Items.Clear();
            DefaultStyleComboBox.Items.Add("(No Default Style)");
            foreach (var style in State.Database.Styles.GetAllStyles().OrderBy(s => s.Name))
                {
                DefaultStyleComboBox.Items.Add(style);
                }
            }

        private void LicenseComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
            {
            if (LicenseComboBox.SelectedItem is string) LicenseComboBox.SelectedItem = null;
            }

        private void DefaultStyleComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
            {
            if (DefaultStyleComboBox.SelectedItem is string) DefaultStyleComboBox.SelectedItem = null;
            }

        }

    }
